<template>
	<div class="content-wrapper">
    <i-cell title-class="cell-title" label-class="cell-label"
      :title="content.ProductName" :label="content.CategoryChar" only-tap-footer>
      <div class="product-content" style="display: block;">
        <span class='product-info' style="display: block;">
          <p class='info-tag'>产品协议：</p>
          <p class='info-content'>{{ content.ProtocolChar }}</p>
        </span>
        <span class='product-info' style="width: 200rpx;">
          <p class='info-tag' style="width: 120rpx;">用户ID：</p>
          <p class='info-content'>{{ content.UserId }}</p>
        </span>
        <span class='product-info' style="width: 440rpx;">
          <p class='info-tag'>创建时间：</p>
          <p class='info-content'>{{ content.CreatedAt }}</p>
        </span>
        <span class='product-info' style="width: 200rpx;">
          <p class='info-tag' style="width: 120rpx;">产品ID：</p>
          <p class='info-content'>{{ content.ID }}</p>
        </span>
        <span class='product-info' style="width: 480rpx;">
          <p class='info-tag' style="width: 80rpx;">Key：</p>
          <p class='info-content'>{{ content.ProductKey }}</p>
        </span>
      </div>
    </i-cell>

    <div class='list' style="margin-top: 30rpx;">

      <div class="list-block">
        <i-icon type="computer" size="48" color="#1EB4C5" />
        <div class='list-info'>
          <span class='info-title'>接入设备总数</span>
          <span class='info-content'>在线设备数量：{{ content.OnlineNum }}台</span>
        </div>
        <span class='list-num'>{{ content.DeviceNum }} 台</span>
      </div>

      <div class="list-block">
        <i-icon type="activity" size="48" color="#1EB4C5" />
        <div class='list-info'>
          <span class='info-title'>总数据点数</span>
          <span class='info-content'>今日新增：{{ toDecimal.DaylyDp }}万条</span>
        </div>
        <span class='list-num'>{{ toDecimal.AllDp }} 万</span>
      </div>

      <div class="list-block">
        <i-icon type="document" size="48" color="#1EB4C5" />
        <div class='list-info'>
          <span class='info-title'>数据模板数量</span>
          <span class='info-content'>暂无</span>
        </div>
        <span class='list-num'>{{ content.StreamNum }} 个</span>
      </div>

    </div>

    <div class="container">

      <i-tabs :current="current1" @change="handleChange1">
          <i-tab key='7' title="最近7天"></i-tab>
          <i-tab key='15' title="最近15天"></i-tab>
          <i-tab key='30' title="最近30天"></i-tab>
      </i-tabs>
      <span class="deviceChart-title">{{ deviceChartTitle }}</span>
      <canvas canvas-id="deviceCanvas" disable-scroll="true" class="canvas" @touchstart="touchHandler1"></canvas>

      <i-tabs style='margin-top: 20rpx;' :current="current2" @change="handleChange2">
          <i-tab key='7' title="最近7天"></i-tab>
          <i-tab key='15' title="最近15天"></i-tab>
          <i-tab key='30' title="最近30天"></i-tab>
      </i-tabs>
      <span class="deviceChart-title">{{ numChartTitle }}</span>
      <canvas style="margin-bottom: 20rpx;" canvas-id="numCanvas" disable-scroll="true" class="canvas" @touchstart="touchHandler2"></canvas>

    </div>

	</div>
</template>

<script>

import store from '../store/store'
import { request, formatTime } from '@/utils/index'
import { transCategory, transProtocol } from '@/utils/dict'

const { $Message } = require('../../../static/dist/base/index')

var WxCharts = require('../../../static/js/wxcharts')

var deviceChart = null
var numChart = null

export default {
  data () {
    return {
      productID: 0,
      content: [],
      deviceTime: 7,
      deviceChartDict: [],
      deviceChartTitle: '最近7天设备接入统计',
      numTime: 7,
      numChartDict: [],
      numChartTitle: '最近7天设备数据量趋势',
      startTime1: 0,
      endTime1: 0,
      current1: '7',
      startTime2: 0,
      endTime2: 0,
      current2: '7',
      timeRange: [7, 15, 30]
    }
  },
  onLoad (options) {
    this.productID = options.productID
    var timeArr1 = this.initTime(this.deviceTime)
    var timeArr2 = this.initTime(this.numTime)
    this.startTime1 = timeArr1[0]
    this.endTime1 = timeArr1[1]
    this.startTime2 = timeArr2[0]
    this.endTime2 = timeArr2[1]

    this.fetchData()
    this.getDeviceChart(this.startTime1, this.endTime1)
    this.getNumChart(this.startTime2, this.endTime2)
  },
  methods: {
    touchHandler1: function (e) {
      deviceChart.showToolTip(e, {
        format: function (item, category) {
          return category + ' ' + item.name + ':' + item.data
        }
      })
    },
    touchHandler2: function (e) {
      numChart.showToolTip(e, {
        format: function (item, category) {
          return category + ' ' + item.name + ':' + item.data
        }
      })
    },
    fetchData () {
      var target = `/api/v1/product/detail?id=${this.productID}`
      request(target, { token: this.token }, 'GET').then((ids) => {
        if (ids.code !== 200) {
          $Message({ content: ids.message, type: 'error' })
          return false
        }
        this.content = this.dataProcess(ids.data)
      }, (e) => {
        $Message({ content: '请求错误，请重试', type: 'error' })
        return false
      })
    },
    initTime (timeRange) {
      var today = new Date()
      today.setHours(0)
      today.setMinutes(0)
      today.setSeconds(0)
      today.setMilliseconds(0)
      var endTime = Date.parse(today) + 86400 * 1000
      var startTime = endTime - 86400 * timeRange * 1000
      return [startTime, endTime]
    },
    getDeviceChart (startTime, endTime) {
      var target = '/api/v1/product/chart?'
      target += `id=${this.productID}`
      target += `&start=${startTime + 8 * 3600 * 1000}&end=${endTime + 8 * 3600 * 1000}`
      request(target, { token: this.token }, 'GET').then((ids) => {
        if (ids.code !== 200) {
          $Message({ content: ids.message, type: 'error' })
          return false
        }
        this.deviceChartDict = this.completeDeviceJoinChartData(startTime, endTime - 86400 * 1000, ids.data)
        this.initDeviceChart()
      }, (e) => {
        $Message({ content: '请求错误，请重试', type: 'error' })
        return false
      })
    },
    getNumChart (startTime, endTime) {
      var target = `/api/v1/datapoint/pscntlist`
      var body = {
        BeginTime: startTime,
        EndTime: endTime,
        ID: parseInt(this.productID),
        DeviceId: parseInt(this.productID),
        Direction: 0,
        token: this.token
      }
      request(target, body, 'POST').then((ids) => {
        if (ids.code !== 200) {
          $Message({ content: ids.message, type: 'error' })
          return false
        }
        this.numChartDict = this.completeDpCntChartData(startTime, endTime - 86400 * 1000, ids.data)
        this.initNumChart()
      }, (e) => {
        $Message({ content: '请求错误，请重试', type: 'error' })
        return false
      })
    },
    handleChange1 (e) {
      this.current1 = e.mp.detail.key
      this.deviceChartTitle = '最近' + this.current1 + '天设备接入数据统计'
      this.deviceTime = parseInt(this.current1)
      var timeArr = this.initTime(this.deviceTime)
      this.startTime1 = timeArr[0]
      this.endTime1 = timeArr[1]
      this.getDeviceChart(this.startTime1, this.endTime1)
    },
    handleChange2 (e) {
      this.current2 = e.mp.detail.key
      this.numChartTitle = '最近' + this.current2 + '天设备数据量趋势'
      this.numTime = parseInt(this.current2)
      var timeArr = this.initTime(this.numTime)
      this.startTime2 = timeArr[0]
      this.endTime2 = timeArr[1]
      this.getNumChart(this.startTime2, this.endTime2)
    },
    initDeviceChart () {
      var res = wx.getSystemInfoSync()
      var windowWidth = res.windowWidth

      deviceChart = new WxCharts({
        canvasId: 'deviceCanvas',
        type: 'line',
        categories: this.deviceChartDict.time,
        animation: true,
        background: '#FFF',
        series: [{
          name: '日接入量',
          data: this.deviceChartDict.new,
          format: function (val, name) {
            return val
          }
        }, {
          name: '日总量',
          data: this.deviceChartDict.total,
          format: function (val, name) {
            return val
          }
        }],
        xAxis: { disableGrid: true },
        yAxis: {
          title: '接入设备统计',
          format: function (val) { return val },
          min: 0
        },
        width: windowWidth,
        height: 200,
        dataLabel: false,
        dataPointShape: true,
        extra: {
          lineStyle: 'curve'
        }
      })
    },
    initNumChart () {
      var res = wx.getSystemInfoSync()
      var windowWidth = res.windowWidth

      numChart = new WxCharts({
        canvasId: 'numCanvas',
        type: 'area',
        categories: this.numChartDict.time,
        animation: true,
        background: '#FFF',
        series: [{
          name: '设备数据量',
          data: this.numChartDict.value,
          format: function (val, name) {
            return val
          }
        }],
        xAxis: { disableGrid: true },
        yAxis: {
          title: '设备数据量',
          format: function (val) { return val },
          min: 0
        },
        width: windowWidth,
        height: 200,
        dataLabel: false,
        dataPointShape: true,
        extra: {
          lineStyle: 'curve'
        }
      })
    },
    completeDeviceJoinChartData (start, end, result) {
      // 获取数据的创建时间戳
      for (var i = 0; i < result.data.length; i++) {
        result.data[i].timestamp = Date.parse(new Date(result.data[i].Created_at.replace('-', '/')))
      }

      var length = (end - start) / 86400 / 1000 + 1
      var timestampArr = []
      var timeArr = []
      var totalNumArr = Array(length).fill(result.total)
      var newNumArr = Array(length).fill(0)

      // 构造时间数组
      for (var j = 0; j < length; j++) {
        var tempTimestamp = 86400 * 1000 * j + start
        timestampArr.push(tempTimestamp)
        timeArr.push(formatTime(tempTimestamp))
      }

      for (var m = 0; m < result.data.length; m++) {
        var index = timestampArr.indexOf(result.data[m].timestamp)
        newNumArr[index] = result.data[m].New
        for (var n = index; n < length; n++) {
          totalNumArr[n] += result.data[m].New
        }
      }

      var newArr = { new: newNumArr, total: totalNumArr, time: timeArr }

      return newArr
    },
    completeDpCntChartData (start, end, result) {
      var length = (end - start) / 86400 / 1000 + 1
      var timeArr = []
      var timestampArr = []
      var daylyArr = Array(length).fill(0)

      // 获取数据的创建时间戳
      // 构造时间数组
      for (var i = 0; i < length; i++) {
        var tempTimestamp = 86400 * 1000 * i + start
        timestampArr.push(tempTimestamp)
        timeArr.push(formatTime(tempTimestamp))
      }
      // 构造值数组
      for (var j = 0; j < result.row.length; j++) {
        var index = timestampArr.indexOf(result.row[j].Ts)
        daylyArr[index] = result.row[j].Value
      }

      var newArr = { value: daylyArr, time: timeArr }
      return newArr
    },
    dataProcess (data) {
      data.CategoryChar = transCategory(data.Category)
      data.ProtocolChar = transProtocol(data.Protocol)
      return data
    }
  },
  computed: {
    token () {
      console.log(store.state.token)
      return store.state.token
    },
    toDecimal () {
      var data = {}
      data.DaylyDp = (this.content.DaylyDp / 10000.0).toFixed(2)
      data.AllDp = (this.content.AllDp / 10000.0).toFixed(2)
      return data
    }
  }
}
</script>

<style>
canvas {
  width: 100%;
  height: 200px;
}
.content-wrapper {
  padding-top: 30rpx;
}
.deviceChart-title {
  display: block;
  margin-top: 20rpx;
  margin-bottom: 20rpx;
  color: #80848f;
  font-size: 14px;
}
.container {
  margin-top: 30rpx;
  margin-bottom: 30rpx;
  padding: 20rpx 0;
  text-align: center;
  width: 100%;
  background-color: #FFF;
  box-shadow: 0 1px 3px rgba(26,26,26,.1);
}
.cell-title {
  display: inline-block;
  color: #1EB4C5;
}
.cell-label {
  display: inline-block;
  font-weight: bolder;
  background-color: #33DEB4;
  font-size: 14px;
  color: #FFF !important;
  padding: 3px 6px;
  margin-left: 15px;
  border-radius: 10px;
}
.product-info {
  width: 300rpx;
  color: #999;
  margin-top: 20rpx;
  display: inline-block;
}
.product-info p {
  display: inline-block;
}
.product-info .info-tag {
  width: 150rpx;
}
.product-info:nth-child(n+2) .info-content {
  color: #1EB4C5;
}
.list {
  box-shadow: 0 1px 3px rgba(26,26,26,.1);
}
.list-block {
  width: 100%;
  height: 150rpx;
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  align-items: center;
  background-color: #FFF;
}
.list-block:nth-child(-n+2) {
  border-bottom: rgba(187, 190, 196, 0.3) 1px dashed;
}
.list-block .list-num {
  width: 200rpx;
  color: #80848f;
  font-size: 44rpx;
}
.list-info {
  width: 220rpx;
  margin-left: -12%;
  display: inline-block;
}
.list-info span {
  display: block;
}
.list-info .info-title {
  color: #80848f;
  font-size: 28rpx;
}
.list-info .info-content {
  font-size: 24rpx;
  margin-top: 10rpx;
  color: #999;
}
</style>